package com.zero.yygh.msm.api;

import com.zero.yygh.common.result.Result;
import com.zero.yygh.common.utils.RandomUtil;
import com.zero.yygh.msm.service.MsmService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author zero
 * @desc 短信发送接口
 * @create 2021/4/2
 */
@Api("短信接口")
@RestController
@RequestMapping("/api/msm")
public class MsmApiController {

    @Resource
    private MsmService msmService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @ApiOperation("发送验证码")
    @GetMapping("send/{phone}")
    public Result<Object> sendCode(@PathVariable String phone) {
        // 从 redis 中获取验证码，如果获取到则返回ok
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return Result.ok();
        }
        // 如果获取不到，则生成
        code = RandomUtil.getSixBitRandom();
        System.out.println(code);
        //调用service方法，通过整合短信服务进行发送
        // boolean isSend = msmService.send(phone,code);
        boolean isSend = true;
        //生成验证码放到redis里面，设置有效时间
        if(isSend) {
            redisTemplate.opsForValue().set(phone, code,2, TimeUnit.MINUTES);
            return Result.ok();
        } else {
            return Result.fail().message("发送短信失败");
        }

    }
}
